package com.namo.cchapi.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.namo.cchapi.entity.PicCaptchaEntity;
import com.namo.cchapi.service.PicCaptchaService;
import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author WangXin
 * @date 2021/4/12 10:41
 */
@RestController
@RequestMapping("/pic_captcha")
@Slf4j
public class PicCaptchaController {

    @Autowired
    PicCaptchaService picCaptchaService;
    @Autowired
    Gson gson;


    @RequestMapping(value = "/check_code",method = RequestMethod.POST)
    public CommonResult checkPicCode(@RequestBody(required = false) String req){
        JsonObject reqObject = gson.fromJson(req, JsonObject.class);
        String id = null;
        String inputCode = null;
        try {
           id = reqObject.get("id").getAsString();
           inputCode = reqObject.get("input_code").getAsString();
        }catch (Exception e){
            log.error(e.getMessage());
            return CommonResult.failed(ResultCode.VALIDATE_FAILED,"请求参数错误");
        }
        boolean result = false;
        try {
            result = picCaptchaService.checkPicCaptcha(id, inputCode);
        }catch (Exception e){
            String message = e.getMessage();
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("验证通过");
    }

    @RequestMapping(value = "/get_code",method = RequestMethod.GET)
    public CommonResult getPicCode(){
        PicCaptchaEntity captcha = null;
        try {
            captcha = picCaptchaService.createPicCaptcha();
        } catch (IOException e) {
            log.error(e.getMessage());
            return CommonResult.failed("生成验证码错误");
        }
        //设置返回的code为空
        captcha.setCode(null);
        return CommonResult.success(captcha);
    }




}
